package com.originskyseed.platform.course.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.course.i18n.CourseResponseMsg;
import com.originskyseed.platform.course.model.Course;
import com.originskyseed.platform.course.model.CourseRelateAnnex;
import com.originskyseed.platform.course.model.CourseRelateRight;
import com.originskyseed.platform.course.model.CourseType;
import com.originskyseed.platform.course.model.TaskSelectCourseVO;
import com.originskyseed.platform.course.service.ICourseRelateAnnexService;
import com.originskyseed.platform.course.service.ICourseRelateIsReadService;
import com.originskyseed.platform.course.service.ICourseRelateRightService;
import com.originskyseed.platform.course.service.ICourseService;
import com.originskyseed.platform.course.service.ICourseTypeService;
import com.originskyseed.platform.course.vo.request.CourseRequestVO;
import com.originskyseed.platform.user.model.Dept;
import com.originskyseed.platform.user.model.Family;
import com.originskyseed.platform.user.model.TradeUnion;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IDeptService;
import com.originskyseed.platform.user.service.IFamilyService;
import com.originskyseed.platform.user.service.IParameterConfigureService;
import com.originskyseed.platform.user.service.ITradeUnionService;

/**
 * 课程表Controller类（OSI_COURSE）
 *
 * @author Tangwanghui
 */
@Controller
@RequestMapping("/course")
@BaseLocaleResource(localeFileName = "i18n_course")
public class CourseController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(CourseController.class);

	@DubboReference
	private ICourseService courseService;

	@DubboReference
	private ICourseTypeService courseTypeService;

	@DubboReference
	private IFamilyService familyService;

	@DubboReference
	private ITradeUnionService tradeUnionService;

	@DubboReference
	private ICourseRelateAnnexService courseRelateAnnexService;

	@DubboReference
	private ICourseRelateRightService courseRelateRightService;

	@DubboReference
	private ICourseRelateIsReadService courseRelateIsReadService;

	@DubboReference
	private IParameterConfigureService parameterConfigureService;

	@DubboReference
	private IDeptService deptService;

	/**
	 * 分页查询
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Course>> courseList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Course>> result = null;
		try {
			// 当前登陆人信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			CourseRequestVO requestVO = this.getParameterBean(CourseRequestVO.class);
			requestVO.setUserId(userInfo.getId());
			if (userInfo.getSourceSys() != 0) {
				// requestVO.setIsOw(1);
				// 查询参数ID --职位层
				/*
				 * ParameterConfigure parameterConfigure = this.parameterConfigureService.selectByCode("EMPLOYEE_POSITION");//查询职位参数父级 List<ParameterConfigure> configureList = this.parameterConfigureService.selectListByParentId(parameterConfigure.getId()); if(configureList != null && configureList.size() > 0){ for (ParameterConfigure configure : configureList) {
				 * if(configure.getCode().equals(userInfo.getType().toString())){ requestVO.setCourseRightId(configure.getId()); break; } } } //查询每一级上级节点 List<String> deptIdList = new ArrayList<>(); Dept dept = this.deptService.selectByPrimaryKey(userInfo.getDeptId()); List<Dept> deptList = new ArrayList<>(); this.selectParentDept(dept.getCode(),deptList); if(deptList != null && deptList.size() > 0){ for (Dept
				 * dept1 : deptList) { deptIdList.add(dept1.getId()); } } requestVO.setDeptIdList(deptIdList);
				 */
				requestVO.setBelongPlatform(userInfo.getSourceSys());
			}
			requestVO.setIsDel(0);
			// 分页查询
			BasePage<Course> page = new BasePage<Course>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.courseService.selectListRelStudyByPage(requestVO.toMap(), page);
			for (Course course:page.getResults()) {
				CourseRelateRight courseRelateRight = new CourseRelateRight();
				courseRelateRight.setCourseId(course.getId());
			    List<CourseRelateRight> list = this.courseRelateRightService.selectList(courseRelateRight);
			    if(list!=null && list.size()>0){
			    	course.setViewRange(1);
					course.setCourseRelateRightList(list);
				}else {
			    	course.setViewRange(0);
				}

				//已读
				Integer isRead = this.courseRelateIsReadService.selectIsRead(course.getId(),userInfo.getId());
			    if(isRead!=null && isRead==2){
			    	course.setIsRead(2);
				}else {
			    	course.setIsRead(1);
				}
			}
			result = new BaseResponseBody<BasePage<Course>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<Course>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 保存信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseSave.json", method = RequestMethod.POST)
	public BaseResponseBody<Course> courseSave(HttpServletRequest request) {
		BaseResponseBody<Course> result = null;
		try {
			// 当前登陆人信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			Course course = this.getParameterBean(Course.class);
			List<CourseRelateRight> courseRelateRightList = this.getParameterList("courseRelateRightList", CourseRelateRight.class);
			List<CourseRelateAnnex> courseRelateAnnexList = this.getParameterList("courseRelateAnnexList", CourseRelateAnnex.class);
			// 获取所属平台
			if (StringUtils.isNotBlank(course.getTypeId())) {
				CourseType courseType = this.courseTypeService.selectByPrimaryKey(course.getTypeId());
				if (courseType != null) {
					course.setBelongPlatform(courseType.getBelongPlatform());
				}
			}

			if (StringUtils.isNotBlank(course.getId())) {
				this.courseService.updateAndFile(course, courseRelateRightList);
			} else {
				// 设置课程id和创建人信息
				// course.setCourseId(createCourseId());
				course.setCreatorId(userInfo.getId());
				course.setCreator(userInfo.getName());
				course.setIsDel(0);
				course.setIsTop(0);
				course.setStatus(1);
				Integer prority = this.courseService.selectPrority();
				if (prority == null) {
					course.setPrority(0);
				} else {
					course.setPrority(prority + 1);
				}
				this.courseService.insertSelectiveAndFile(course, courseRelateRightList, courseRelateAnnexList);
			}
			result = new BaseResponseBody<Course>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), course);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Course>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 删除信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/courseDelete.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids" })
	public BaseResponseBody<Boolean> courseDelete(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});

			this.courseService.updateDelByIds(Arrays.asList(ids));
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 批量修改状态
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateCourseStatus.json", method = RequestMethod.POST)
	@RequiredParams(names = { "ids", "status" })
	public BaseResponseBody<Boolean> updateCourseStatus(HttpServletRequest request) {
		BaseResponseBody<Boolean> result = null;
		try {
			// 请求参数
			String[] ids = this.getParameterArray("ids", new String[] {});
			Integer status = this.getParameterInteger("status", null);

			Map<String, Object> map = new HashMap<>();
			map.put("list", Arrays.asList(ids));
			map.put("status", status);

			this.courseService.updateStatusByIds(map);
			result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.OPERATION_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.OPERATION_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 通过课程id查询详情
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectCourseById.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody selectCourseById(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			String id = this.getParameterString("id", null);

			Course course = this.courseService.selectByPrimaryKey(id);

			CourseRelateAnnex courseRelateAnnex = new CourseRelateAnnex();
			courseRelateAnnex.setCourseId(id);
			List<CourseRelateAnnex> courseRelateAnnexList = this.courseRelateAnnexService.selectList(courseRelateAnnex);

			CourseRelateRight courseRelateRight = new CourseRelateRight();
			courseRelateRight.setCourseId(id);
			List<CourseRelateRight> courseRelateRightList = this.courseRelateRightService.selectList(courseRelateRight);
			course.setCourseRelateAnnexList(courseRelateAnnexList);
			course.setCourseRelateRightList(courseRelateRightList);

			CourseType courseType = this.courseTypeService.selectByPrimaryKey(course.getTypeId());
			if (courseType != null) {
				course.setCourseType(courseType.getName());
			}
			//已读
			this.courseRelateIsReadService.updateIsRead(id,userInfo.getId());
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), course);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询学习进度
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserStudySituation.json")
	public BaseResponseBody selectUserStudySituation(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			List<Map<String, Object>> list = new ArrayList<>();
			// 当前登陆人信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);

			String taskId = this.getParameterString("taskId", null);

			// 查询阶段
			Map<String, Object> queryMap = new HashMap<>();
			queryMap.put("taskId", taskId);
			queryMap.put("userId", userInfo.getId());
			List<Course> courseList = this.courseService.selectUserStudySituationList(queryMap);
			for (Course course : courseList) {
				Map<String, Object> map = new HashMap<>();
				map.put("name", course.getName());
				if (course.getCompleteStatus() != null && course.getCompleteStatus() == 1) {
					map.put("status", 2);
					map.put("time", course.getCompleteTime());
				} else {
					Integer prority = course.getCouPrority();
					if (prority != null) {
						if (prority == 1) {
							map.put("status", 1);
						} else {
							queryMap.put("prority", prority - 1);
							Integer status = this.courseService.selectStatusByPrority(queryMap);
							if (status != null && status == 1) {
								map.put("status", 1);
							} else {
								map.put("status", 0);
							}
						}
					} else {
						map.put("status", 0);
					}
					map.put("time", null);
				}
				list.add(map);
			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), list);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 修改置顶信息
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateIsTop.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id" })
	public BaseResponseBody updateIsTop(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);

			Course course = new Course();
			course.setId(id);
			course.setIsTop(1);
			course.setUpdateTime(new Date());
			this.courseService.updateIsTop(course);
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 升序降序
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUpOrDown.json", method = RequestMethod.POST)
	@RequiredParams(names = { "id", "upOrDown", "prority" })
	public BaseResponseBody updateUpAndDown(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			// 请求参数
			String id = this.getParameterString("id", null);
			Integer upOrDown = this.getParameterInteger("upOrDown", null);
			Integer prority = this.getParameterInteger("prority", null);
			Integer updatePrority = prority;

			// 等于0是升序 1是降序
			if (upOrDown == 0) {
				prority += 1;
			} else {
				prority -= 1;
			}
			// 将另外一个升序或降序
			Course course = this.courseService.selectCourseByPrority(prority);
			if (course != null) {
				course.setPrority(updatePrority);
			}

			Course updateCourse = new Course();
			updateCourse.setId(id);
			updateCourse.setPrority(prority);
			if (course != null) {
				this.courseService.updatePrority(course, updateCourse);
			} else {
				this.courseService.updateByPrimaryKeySelective(updateCourse);
			}

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_SUCCESS.getMsg()), true);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.SAVE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询主播和公会
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectFamilyTradeUnion.json", method = RequestMethod.POST)
	public BaseResponseBody selectFamilyTradeUnion(HttpServletRequest request) {
		BaseResponseBody result = null;
		try {
			Map<String, Object> map = new HashMap<>();
			List<Family> familyList = this.familyService.selectList(new Family());
			List<TradeUnion> tradeUnionList = this.tradeUnionService.selectList(new TradeUnion());
			map.put("familyList", familyList);
			map.put("tradeUnionList", tradeUnionList);

			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_SUCCESS.getMsg()), map);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DELETE_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 分页查询用户课程列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserCourseList.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<Course>> selectUserCourseList(HttpServletRequest request) {
		BaseResponseBody<BasePage<Course>> result = null;
		try {
			// 当前登陆人信息
			UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
			// 请求对象
			CourseRequestVO requestVO = this.getParameterBean(CourseRequestVO.class);
			requestVO.setUserId(userInfo.getId());

			// 分页查询
			BasePage<Course> page = new BasePage<Course>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.courseService.selectUserCourseByPage(requestVO.toMap(), page);

			Map<String, Object> map = new HashMap<>();
			map.put("taskId", requestVO.getTaskId());
			map.put("userId", userInfo.getId());
			// 判断是否要上锁
			for (int i = 0; i < page.getResults().size(); i++) {
				Course course = page.getResults().get(i);
				if (course.getCompleteStatus() != null && course.getCompleteStatus() == 1) {
					course.setIsLock(0);
				} else {
					Integer prority = course.getCouPrority();
					if (prority != null) {
						if (prority == 1) {
							course.setIsLock(0);
						} else {
							map.put("prority", prority - 1);
							Integer status = this.courseService.selectStatusByPrority(map);
							if (status != null && status == 1) {
								course.setIsLock(0);
							} else {
								course.setIsLock(1);
							}
						}
					} else {
						course.setIsLock(1);
					}
				}

			}
			result = new BaseResponseBody(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 任务发布课程选择列表
	 *
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectTaskCourseByPage.json")
	@RequiredParams(names = { "pageNo", "pageSize" })
	public BaseResponseBody<BasePage<TaskSelectCourseVO>> selectTaskCourseByPage(HttpServletRequest request) {
		BaseResponseBody<BasePage<TaskSelectCourseVO>> result = null;
		try {
			// 请求对象
			CourseRequestVO requestVO = this.getParameterBean(CourseRequestVO.class);
			// 分页查询
			BasePage<TaskSelectCourseVO> page = new BasePage<TaskSelectCourseVO>(requestVO.getPageNo(), requestVO.getPageSize());
			page = this.courseService.selectTaskCourseByPage(requestVO.toMap(), page);
			result = new BaseResponseBody<BasePage<TaskSelectCourseVO>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_SUCCESS.getMsg()), page);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			result = new BaseResponseBody<BasePage<TaskSelectCourseVO>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), CourseResponseMsg.DATA_ERROR.getMsg()), e.getMessage(), null);
		}
		return result;
	}

	/**
	 * 查询每一上级
	 *
	 * @param code
	 * @param deptList
	 * @throws Exception
	 */
	private void selectParentDept(String code, List<Dept> deptList) throws Exception {
		Dept dept = this.deptService.selectByCode(code);
		deptList.add(dept);
		if (dept.getType() == 0) {
			return;
		} else {
			selectParentDept(dept.getParentCode(), deptList);
		}
	}

	/**
	 * 获取课程id
	 *
	 * @return
	 * @throws Exception
	 */
	/*
	 * private String createCourseId () throws Exception{ //获得当前时间戳 Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss"); String dateString = formatter.format(currentTime); //生成随机数（随机数范围：1000到10000） int num = (int) (Math.random() * (10000 - 1000) + 1000); dateString += num;
	 *
	 * // 判断id是否已存在 String courseTypeId = this.courseService.selectCourseId(dateString); if(StringUtils.isNotEmpty(courseTypeId)){ return createCourseId(); }else { return dateString; } }
	 */

}
